/*
 * @Author: SailorCai
 * @Date: 2020-12-08 22:21:40
 * @LastEditors: SailorCai
 * @LastEditTime: 2020-12-09 00:06:33
 * @FilePath: /chat/client/src/store/index.ts
 */
import { createStore, combineReducers } from 'redux'
import { DefaultRootState, ReactReduxContextValue } from 'react-redux'
import { ReducerAction } from 'react';
import {CTX_KEY} from '@/constants'
import { getUserCtx } from '@/utils/tool'

declare interface DefaultRootState_s extends DefaultRootState {
  chator?: any,
  appContext?: any
}

const chator = (state = {}, action: any) => {
  switch (action.type) {
    case 'UPDATE_CHATER':
      return action.payload;
    default: 
      return state;
  }
}
type CTX = {
  token: string,
  user: object
};
const appContext = (state = {token: '', user: {}}, action: any) => {
  let data: CTX;
  switch (action.type) {
    case 'UPDATE_appContext':
      localStorage.setItem(CTX_KEY, JSON.stringify(action.payload));
      (window as any).$ctx = getUserCtx();
      return action.payload;
    case 'UPDATE_TOKEN':
      // 先保存到localStorage
      data = Object.assign({}, state, {token: action.payload});
      localStorage.setItem(CTX_KEY, JSON.stringify(data));
      return data;
    case 'UPDATE_USER':
      data = Object.assign({}, state, {user: action.payload});
      localStorage.setItem(CTX_KEY, JSON.stringify(data));
      return data;
    default: 
      return state;
  }
}

declare type ChatInstance = {
  msg: string,
  from: string
}

const hallChat = (state: any = {}, action: any) => {
  switch(action.type) {
    case 'update_hall':
      for(var key in action.payload) {
        state[key] = state[key] || [];
        state[key].push(action.payload[key]);
      }
      return Object.assign({}, state);
    default: 
      return state;
  }
}

const msgStatus = (state: any = {}, action: any) => {
  switch(action.type) {
    case 'UpdateMsgStatus':
      state[action.payload.id] = state[action.payload.id] || {num: 0, latest: ''}
      state.all = state.all || {num: 0, latest: ''}
      state[action.payload.id].num += 1;
      state.all.num += 1;
      state[action.payload.id].latest = action.payload.latest;
      return Object.assign({}, state);
    case 'clearMsgStatus':
      state[action.payload.id] = state[action.payload.id] || {num: 0, latest: ''}
      state.all = state.all || {num: 0, latest: ''};
      state.all.num -= state[action.payload.id].num;
      state[action.payload.id].num = 0;
      return Object.assign({}, state);
      default: 
    return state;
  }
}

export const store = createStore(combineReducers({
  chator,
  appContext,
  hallChat,
  msgStatus
}));